#!/usr/bin/python
import logging
import time
import json
import urllib2
import re
from root import application as app
from root.utils import ClubListReader as club_reader
import os
LOCAL = False
try:
	from google.appengine.api import rdbms
except:
	print "local version"
	LOCAL = True

_INSTANCE_NAME='dublin-nightsdb:instance1'

START_TIME = int(time.time() - 86400)


'''
	Read access token from file
'''
def get_access_token() :
	
	try:
		token_path = os.path.join(os.path.dirname(app.__file__), 'token') 
		f = open(token_path, 'r')
		access_token = 'access_token=' + f.read() 
		f.close()
	except:
		logging.error("Could not retrieve access token.")
	return access_token


def get_event_details(event_id):

	access_token = get_access_token()
	resp = urllib2.urlopen('https://graph.facebook.com/'+str(event_id)+'?'+access_token)
	result = json.loads(resp.read())
	resp = urllib2.urlopen('https://graph.facebook.com/'+str(event_id)+'/picture?type=normal&redirect=false&'+access_token)	
	picurl = json.loads(resp.read())
	result['picurl'] = picurl['data']['url']
	return result


def get_events(uid):
	
#	QUERY = "SELECT eid FROM event WHERE creator = "+str(uid)+" AND eid IN (SELECT eid FROM event_member WHERE uid = "+str(uid)+") AND start_time > "+str(START_TIME)+" ORDER BY start_time"
	QUERY = "SELECT eid FROM event WHERE creator = "+str(uid)+" AND eid IN (SELECT eid FROM event_member WHERE uid = "+str(uid)+") "
	
	access_token = get_access_token()
	url = 'https://graph.facebook.com/fql?q='+QUERY+'&'+access_token

	#remove duplicate spaces
	formattedurl = re.sub(' +',' ', url)
	formattedurl = re.sub(' ','%20', formattedurl)
	resp = urllib2.urlopen(formattedurl)
	result = json.loads(resp.read())['data']
	resp = urllib2.urlopen('https://graph.facebook.com/'+str(uid)+'/picture?type=normal&redirect=false&'+access_token)	
	picurl = json.loads(resp.read())
	new_result = []
	for event_id in result:
		event_id['url'] = str(picurl['data']['url'])
		new_result.append(event_id)
	return new_result	


events = []

#get list of club ids
club_id_list = club_reader.readClubsId()

# get events for each club
for club_id in club_id_list :
	events.append(get_events(club_id))
	
events = sum(events,[])
queries = []
num_events = 0
# process each event
for event_id in events:
	
	try:
		event =  get_event_details(event_id['eid'])
		eventID = event['id']		
		clubID = event['owner']['id']
		clubName = event['owner']['name']
		age = 18
		entryPrice = -1

		vip = 1 if event['description'].find("VIP") > 0 else 0
		eventDescription = event['description']
		
		location = event['location']
		date, startTime = event['start_time'].split("T")
		drinkspromos = "<blank>"
		promoted = 0
		EventPicURL = event['picurl']# 'https://graph.facebook.com/'+str(event_id['eid'])+'/picture?type=square'
		ClubPicURL = event_id['url']
		eventName = event['name']
		eventLink = 'https://www.facebook.com/events/'+ event['id']
		clubQuery = """INSERT INTO clubs VALUES (%d, '%s', '%s', %d, '%s', '%s') ON DUPLICATE KEY UPDATE ClubPicURL= '%s'""" % (int(clubID) , clubName, location, 0, 'email@example.com', ClubPicURL, ClubPicURL)
		eventQuery = """REPLACE INTO events VALUES (%d, %d, %d, %d, %d, '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s')""" % (int(eventID), int(clubID), age, entryPrice, vip, str(startTime), str(date), drinkspromos, promoted, EventPicURL, eventDescription.replace("'", '').encode('unicode-escape'), location, eventName.replace("'", '').encode('unicode-escape'), eventLink, time.asctime(time.strptime(str(date), '%Y-%m-%d')).split(' ')[0])
	
		queries.append((clubQuery,eventQuery))
		num_events = num_events + 1
		
	except:
		logging.error('Something went wrong with event: %s.  Club ID: %s\n' %(event['id'], event['owner']['id']))

# fill database
if LOCAL == False:
	conn = rdbms.connect(instance=_INSTANCE_NAME, database="mysql")
	c = conn.cursor()

	for query in queries:
		c.execute(query[0])
		c.execute(query[1])
	
	conn.commit()
	conn.close()

logging.debug("Added %s events to database." % num_events)
